#include"VideoBase.h"
#include "models/command.h"

#include <MainWindow.h>
#include <QTimer>
#include <QVBoxLayout>

#include <models/imagemodel.h>
#include <models/videomodel.h>

#include <webrtc/photodialog.h>

void VideoBase::setShowMax(bool newShowMax)
{
    m_bShowMax = newShowMax;
    if(m_bShowMax) //最大化时按钮显示在右侧
    {
        m_pPhotoBtn->setGeometry(width() - int(70*g_xScale), height()/2 - int(70*g_xScale),int(60*g_xScale),int(60*g_xScale));
        m_pVideoBtn->setGeometry(width() - int(70*g_xScale), height()/2 + int(10*g_xScale),int(60*g_xScale),int(60*g_xScale));
        m_pRecordLab->setGeometry( width() - int(179*g_xScale),height()/2 + int(10*g_xScale),int(100*g_xScale),int(60*g_xScale));
    }
    else //不是最大化时显示在右下角
    {
        m_pPhotoBtn->setGeometry(width() - int(35*g_xScale), height() - int(70*g_xScale),int(30*g_xScale),int(30*g_xScale));
        m_pVideoBtn->setGeometry(width() - int(35*g_xScale), height()- int(35*g_xScale),int(30*g_xScale),int(30*g_xScale));
        m_pRecordLab->setGeometry( width() - int(140*g_xScale),height()- int(35*g_xScale),int(100*g_xScale),int(30*g_xScale));
    }
    m_pPhotoBtn->raise();
    m_pVideoBtn->raise();
}

VideoBase::VideoBase(QWidget *parent):
    QWidget(parent)
    , m_strUrl("")
    , m_bPlaying(false)
{
    initButtons();
    initStatusContainer();  // 初始化状态容器
    m_pRecordTimer  = new QTimer(this);
    m_nRecordSeconds= 0;
    connect(m_pRecordTimer,&QTimer::timeout,this,[this](){
        m_nRecordSeconds++;
        int hours = m_nRecordSeconds / 3600;
        int minutes = (m_nRecordSeconds % 3600) / 60;
        int seconds = m_nRecordSeconds % 60;

        QString timeStr = QString("%1:%2:%3")
                              .arg(hours, 2, 10, QChar('0'))
                              .arg(minutes, 2, 10, QChar('0'))
                              .arg(seconds, 2, 10, QChar('0'));

        m_pRecordLab->setText(timeStr);
    });

    m_pReconnectTimer = new QTimer(this);
    m_nReconnectSeconds = 0;
    connect(m_pReconnectTimer, &QTimer::timeout, this, [this]() {
        m_nReconnectSeconds--;
        if (m_nReconnectSeconds > 0) {
            m_pStatusLabel->setText(QString("连接失败\r\n%1后重试...").arg(makeTimeString(m_nReconnectSeconds)));
        } else {
            if (m_pReconnectTimer) {
                m_pReconnectTimer->stop();
            }
            if (m_pReconnectTimer) {
                startPlay();
            }
        }
    });
}

VideoBase::~VideoBase()
{


}

void VideoBase::setUrl(QString strUrl)
{
    m_strUrl = strUrl;
}

QString VideoBase::strUrl() const
{
    return m_strUrl;
}

QString VideoBase::makeTimeString(int seconds)
{
    QString timeStr;
    if (seconds >= 3600) {
        int hours = seconds / 3600;
        int minutes = (seconds % 3600) / 60;
        int secs = seconds % 60;
        timeStr = QString("%1小时%2分钟%3秒").arg(hours).arg(minutes).arg(secs);
    } else if (seconds >= 60) {
        int minutes = seconds / 60;
        int secs = seconds % 60;
        timeStr = QString("%1分钟%2秒").arg(minutes).arg(secs);
    } else {
        timeStr = QString("%1秒").arg(seconds);
    }
    return timeStr;
}
void VideoBase::initButtons()
{
    m_pPhotoBtn = new TouchButton(this);
    m_pPhotoBtn->setStyleSheet("QPushButton{ "
                               "  background-color:transparent;"
                               "  border-image: url(:/images/video_photo.png);"
                               "} "
                               "QPushButton:pressed{"
                               "  border-image: url(:/images/video_photo_pressed.png);"
                               "}");
    m_pPhotoBtn->show();
    m_pVideoBtn = new TouchButton(this);
    m_pVideoBtn->setStyleSheet("QPushButton{ "
                               "  background-color:transparent;"
                               "  border-image: url(:/images/video_record.png);"
                               "} "
                               "QPushButton:pressed{"
                               "  border-image: url(:/images/video_record_pressed.png);"
                               "}");
    m_pVideoBtn->show();
    connect(m_pPhotoBtn, &QPushButton::clicked,this,[this](){takePhoto();});
    connect(m_pVideoBtn, &QPushButton::clicked,this,[this](){
        if(isRecording())
            stopRecording(false);
        else
            startRecording();
    });
    m_pRecordLab = new QLabel(this);
    m_pRecordLab->setStyleSheet(QString("QLabel{"
                                        "background-color:transparent;"
                                        "color:#FF0000;"
                                        "font:%1px \"微软雅黑\"; "
                                        "border: 0px; "
                                        "}").arg(int(18*g_xScale)));
    m_pRecordLab->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    m_pRecordLab->show();
}

void VideoBase::initStatusContainer()
{
    // 创建状态标签和按钮的容器
    m_pStatusContainer = new QWidget(this);
    m_pStatusContainer->setStyleSheet(" background-color: rgb(0, 0, 0);border: 0px; ");
    QVBoxLayout* statusLayout = new QVBoxLayout(m_pStatusContainer);

    // 创建状态标签
    m_pStatusLabel = new QLabel(m_pStatusContainer);
    m_pStatusLabel->setAlignment(Qt::AlignCenter);

    m_pStatusLabel->setStyleSheet(QString("QLabel { color: white; \
                                          font: %1px \"微软雅黑\"; }").arg(int(18*g_xScale)));

    // 创建立即重连按钮
    m_pReconnectButton = new TouchButton("立即重连", m_pStatusContainer);
    m_pReconnectButton->setFixedSize(int(120*g_xScale), int(60*g_yScale));
    m_pReconnectButton->setStyleSheet(
        QString("QPushButton { "
                "   color: white; "
                "   font: %1px \"微软雅黑\";"
                "   background-color:#007BFF; "
                "   border: none; "
                "   padding: 5px 15px; "
                "   border-radius: 4px; "
                "   margin-top: 10px; "
                "} "
                "QPushButton:pressed { "
                "   background-color: #0056b3; "
                "} ").arg(int(18*g_xScale))
        );
    // 连接立即重连按钮的点击事件
    connect(m_pReconnectButton, &QPushButton::clicked, this, [this]() {
        startPlay();
    });

    // 将标签和按钮添加到垂直布局中
    statusLayout->addWidget(m_pStatusLabel);
    statusLayout->addWidget(m_pReconnectButton, 0, Qt::AlignCenter);
    statusLayout->setAlignment(Qt::AlignCenter);
    statusLayout->setSpacing(0);

    // 设置容器样式为透明
    m_pStatusContainer->setStyleSheet(
        "QWidget { "
        "   background-color: transparent; "
        "}"
        );

    // 创建垂直布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    // 将容器添加到主布局中
    layout->addWidget(m_pStatusContainer);
    layout->setAlignment(m_pStatusContainer, Qt::AlignCenter);

    // 确保容器始终显示在 m_pWebView 上面
    //m_pStatusContainer->raise();
    m_pStatusContainer->show();
    m_pReconnectButton->hide();
}

void VideoBase::onConnectFail()
{
    m_nReconnectSeconds = 10 * (1 << (m_nTestCount));
    if(m_nReconnectSeconds > 86400)
        m_nReconnectSeconds = 86400;
    m_pStatusLabel->setText(QString("连接失败\r\n%1后重试...").arg(makeTimeString(m_nReconnectSeconds)));
    m_pStatusContainer->show();
    m_pReconnectButton->show();
    m_pStatusContainer->raise();
    m_pReconnectTimer->start(1000);

}

void VideoBase::onConnecting()
{
    m_pStatusLabel->setText("正在连接...");
    m_pStatusContainer->show();
    m_pReconnectButton->hide();
    m_pReconnectTimer->stop();
}

void VideoBase::onConnectSucc()
{
    m_pStatusContainer->hide();
    if(m_bRecording)
    {
        startRecording();
    }
}

void VideoBase::onRecordEnd(QString strFile)
{
    VideoModel::getInstance()->insertVideo(strFile);
}

void VideoBase::onTakePhoto(QString strFile)
{
    ImageModel::getInstance()->insertImage(strFile);

    // 显示截图对话框
    PhotoDialog *dialog = new PhotoDialog(strFile, MainWindow::getInstance());
    dialog->setAttribute(Qt::WA_DeleteOnClose);
    dialog->show();
}

void VideoBase::onStopTimer()
{
    stopVideo(false);
    m_StopTimer.stop();
}

void VideoBase::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    if(m_bShowMax) //最大化时按钮显示在右侧
    {
        m_pPhotoBtn->setGeometry(width() - int(70*g_xScale), height()/2 - int(70*g_xScale),int(60*g_xScale),int(60*g_xScale));
        m_pVideoBtn->setGeometry(width() - int(70*g_xScale), height()/2 + int(10*g_xScale),int(60*g_xScale),int(60*g_xScale));
        m_pRecordLab->setGeometry( width() - int(179*g_xScale),height()/2 + int(10*g_xScale),int(100*g_xScale),int(60*g_xScale));
    }
    else //不是最大化时显示在右下角
    {
        m_pPhotoBtn->setGeometry(width() - int(35*g_xScale), height() - int(70*g_xScale),int(30*g_xScale),int(30*g_xScale));
        m_pVideoBtn->setGeometry(width() - int(35*g_xScale), height()- int(35*g_xScale),int(30*g_xScale),int(30*g_xScale));
        m_pRecordLab->setGeometry( width() - int(140*g_xScale),height()- int(35*g_xScale),int(100*g_xScale),int(30*g_xScale));
    }
    m_pPhotoBtn->raise();
    m_pVideoBtn->raise();
    m_pRecordLab->raise();
}

void VideoBase::showEvent(QShowEvent *event)
{
    if(!m_bPlaying)
        startPlay();
    m_StopTimer.stop();
    QWidget::showEvent(event);
}

void VideoBase::hideEvent(QHideEvent *event)
{
    if(!m_bRecording)
    {
        connect(&m_StopTimer, &QTimer::timeout,this, &VideoBase::onStopTimer,Qt::UniqueConnection);
        m_StopTimer.start(2000);
    }
    else
        setMute(true);
    QWidget::hideEvent(event);
}
